from flask import Flask, request
from flask_cors import CORS
from shared import db, bcrypt, migrate, jwt
from config import Config
import logging
import json
from utils import response

def create_app():
    app = Flask(__name__, static_folder='public')
    app.config.from_object(Config)
    print(app.config)

    # Initialize extensions
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app,app.config['JWT_SECRET_KEY'])
    bcrypt.init_app(app)
    CORS(app, resources={r"/api/*": {"origins": "*"} })

    # 注册路由蓝图
    from routes.users import users_bp
    from routes.upload import upload_bp
    from routes.chats import chats_bp
    from routes.roles import roles_bp
    from routes.search import hot_search_bp

    app.register_blueprint(users_bp, url_prefix='/api/users')
    app.register_blueprint(upload_bp, url_prefix='/api/upload')
    app.register_blueprint(roles_bp, url_prefix='/api/roles')
    app.register_blueprint(chats_bp, url_prefix='/api/chats')
    app.register_blueprint(hot_search_bp, url_prefix='/api/search')

    return app

flask_app = create_app()

@flask_app.before_request
def log_request_info():
    try:
        body = request.get_data().decode('utf-8') if request.method == 'POST' else None
    except UnicodeDecodeError:
        body = None
    request_data = {
        "path": request.path,
        "method": request.method,
        "remote": request.remote_addr,
        "headers": dict(request.headers),
        "query": dict(request.args),
        "body": body
    }
    logging.info(json.dumps(request_data, indent=4))

# 自定义错误处理
@jwt.unauthorized_loader
def unauthorized_response(callback):
    return response(False, message='Unauthorized', status=7401)

@jwt.invalid_token_loader
def invalid_token_response(callback):
    return response(False, message='Invalid Token', status=7422)

@jwt.expired_token_loader
def expired_token_response(jwt_header, jwt_payload):
    return response(False, message='Token has expired', status=7402)